import axios from 'axios'
import store from '../store'
import cryptoJs from 'crypto-js';
import { apiAuthorization, apiChannelAuthorization } from './utils/signature';
import { Navigate } from "react-router-dom";
if(localStorage.getItem('userinfo')==undefined){
  window.location.hash='/login'
}
// create an axios instance
const service = axios.create({
  baseURL: 'https://api.codler.cn/', // url = base url + request url
  timeout: 50000 // request timeout
})

// request interceptor
service.interceptors.request.use(async config => {
    config.headers['Content-Type'] = 'application/json';
  // api-type : 1-接口授权签名；2-通常参数加密；3-通常参数加密+接口授权签名
  if (config.headers['api-type'] == 1)
    apiAuthorization(config.headers, config.data);
  if (config.headers['api-type'] == 2)
    config.data = await apiChannelAuthorization(config.headers, config.data);
  if (config.headers['api-type'] == 3) {
    config.data = await apiChannelAuthorization(config.headers, config.data);
    apiAuthorization(config.headers, config.data);
  }
  console.log(config)
  return config
  
}, error => {
  //请求拦截错误处理
  console.log('请求拦截器错误', error)

})

// response interceptor
service.interceptors.response.use(
  response => {
    console.log(response)
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      console.error(response)
    }
  },
  error => {
    // console.log(error.response.status) // for debug
    if(error.response.status==403){
    console.log('需要跳转到登录页面')
    window.location.hash='/login'
    return Promise.resolve(error)
    
  }
}
)



export default service
